// import CryptoJS from './crypto-js'

import CryptoJS from 'crypto-js'

// 加解密报文
const key = 'mmL9pP7Cdyqewm7b'
const iv = '19PW6mSGoSjqLbjF'

export function encrypt(data) {
  //key,iv：16位的字符串
  const u = data
  // var	l = CryptoJS.enc.Base64.stringify(u);
  const key1 = CryptoJS.enc.Utf8.parse(key)
  const iv1 = CryptoJS.enc.Utf8.parse(iv)
  const ecrypted = CryptoJS.AES.encrypt(u, key1, {
    iv: iv1,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return ecrypted.toString()
}

export function decrypt(data = '') {
  //key,iv：16位的字符串
  const u = CryptoJS.enc.Hex.parse(data)
  const l = CryptoJS.enc.Base64.stringify(u)
  const key1 = CryptoJS.enc.Utf8.parse(key)
  const iv1 = CryptoJS.enc.Utf8.parse(iv)
  const decrypted = CryptoJS.AES.decrypt(l, key1, {
    iv: iv1,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

// HMACSHA256加密
export function HmacSHA256(message, key) {
  const hash = CryptoJS.HmacSHA256(message, key).toString()
  return hash
}

// 获取32位随机字符串
export function getNonce() {
  let nonceStr = ''
  const strArr = 'abcdefghigklmnopqrstuvwxyz0123456789'
  const strNum = strArr.length
  for (let i = 0; i < 32; i++) {
    const index = Math.floor(Math.random() * strNum)
    nonceStr += strArr[index]
  }
  return nonceStr
}

//签名
export function getSign(header, data = {}) {
  const headerValAll = Object.values(header)
  if (Object.keys(data)?.length) {
    headerValAll.push(JSON.stringify(data))
  }
  const salt = getApp().globalData.salt
  const sortAll = headerValAll.sort()
  const message = sortAll.join('')
  const sign = HmacSHA256(message, salt)
  return sign
}
